﻿using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WucCloud.Database;
using WucCloud.Entity;
using WucCloud.Utility;

namespace WucCloud.Application
{
    /// <summary>
    /// 菜单信息服务
    /// </summary>
    public class MenuInfoService :BaseService<MenuInfoEntity>,IDependency
    {
        /// <summary>
        /// 子类构造函数
        /// </summary>
        /// <param name="menuRepository"></param>
        public MenuInfoService(IBaseRepository<MenuInfoEntity> menuRepository, IUnitOfWork unitOfWork)
        {
            base._repository = menuRepository;
            base._unitOfWork = unitOfWork;
        }

        #region 获取数据

        /// <summary>
        /// 通过Id查询
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <returns></returns>
        public async Task<MenuInfoEntity> FindById(string keyId)
        {
            try
            {
                //通过Id查询角色数据
                var entity = await _repository.FindByIdAsync(keyId);
                return entity;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 自定义条件查询
        /// </summary>
        /// <param name="keyvalue">查询条件（编码/名称）</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<MenuInfoEntity>> GetList(string keyvalue)
        {
            try
            {
                //得到所有菜单信息数据
                var data = await _repository.QueryableAsync(t => t.IsEnabled == true && t.IsDeleted == false);

                //条件查询 通过编码/名称查询
                if (!string.IsNullOrEmpty(keyvalue))
                {
                    data = data.FindAll(t => t.EnCode.Contains(keyvalue) || t.MenuName.Contains(keyvalue));
                }
                if (data.Count == 0)
                {
                    throw new Exception("查无数据");
                }
                return data;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 自定义条件分页查询
        /// </summary>
        /// <param name="keyvalue">查询条件(编码/名称)</param>
        /// <param name="page">分页组件类</param>
        /// <returns></returns>
        public async Task<List<MenuInfoEntity>> QueryPagedList(string keyvalue, PageModel page)
        {
            try
            {
                //获取角色分页数据
                var entity = await _repository.SugarQueryable()
                    .Where(t => t.IsEnabled == true && t.IsDeleted == false)
                    .ToOffsetPageAsync(page.PageIndex, page.PageSize);

                //条件查询 根据编码/角色名称查询
                if (!string.IsNullOrEmpty(keyvalue))
                {
                    entity = entity.FindAll(t => t.EnCode.Contains(keyvalue) || t.MenuName.Contains(keyvalue));
                }

                return entity;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 保存数据（新增/编辑）
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <param name="entity">实体信息</param>
        /// <returns></returns>
        public async Task<bool> SaveChange(string keyId, MenuInfoEntity entity)
        {
            try
            {
                //新增
                if (string.IsNullOrEmpty(keyId))
                {
                    #region 数据校验
                    var data = await _repository.AnyAsync(t => t.MenuName == entity.MenuName);
                    if (data == true)
                    {
                        throw new Exception("菜单已存在，请重新输入");
                    }
                    //非空校验
                    if (string.IsNullOrEmpty(entity.EnCode) || string.IsNullOrEmpty(entity.MenuName))
                    {
                        throw new Exception("编码/名称不可为空");
                    }
                    #endregion

                    //数据初始化
                    entity.KeyId = IDGenerator.CreateNewId();
                    entity.IsEnabled = true;
                    entity.IsDeleted = false;
                    entity.CreateTime = DateTime.Now;
                    entity.CreateUserId = GlobalContext.CurrentUser().KeyId;
                    entity.CreateUserName = GlobalContext.CurrentUser().RealName;

                    return await _repository.InsertAsync(entity);
                }
                //编辑
                else
                {
                    //数据初始化
                    entity.KeyId = keyId;
                    entity.IsEnabled = true;
                    entity.IsDeleted = false;
                    entity.UpdateTime = DateTime.Now;
                    entity.UpdateUserId = GlobalContext.CurrentUser().KeyId;
                    entity.UpdateUserName = GlobalContext.CurrentUser().RealName;

                    return await _repository.UpdateAsync(entity);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> Deleteable(string keyId)
        {
            try
            {
                var data = await _repository.QueryableAsync(t => t.ParentId.Equals(keyId));
                if (data.Count > 0)
                {
                    throw new Exception("删除失败，操作的数据包含了下级菜单");
                }
                else
                {
                    bool result = await _repository.DeleteAsync(keyId);
                    if (!result)
                    {
                        throw new Exception("删除失败");
                    }
                    return result;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }
        #endregion
    }
}
